/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fresher.servletcontroller;

import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import hapax.TemplateException;
import hapax.TemplateLoader;
import hapax.TemplateResourceLoader;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fresher.model.BillDetailModel;
import fresher.model.BillModel;
import fresher.objects.Bill;
import fresher.objects.BillDetail;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author nguyenbt
 */
public class BillDetailServletController extends HttpServlet {
    
    private String billID = "";
    private Bill bill = null;
    private static final String STATIC_HOST = "http://localhost:8080";
    
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        // get parameters
        String reqBillID = request.getParameter("bid");
//        System.out.println("reqBillID ="+reqBillID);
        
        // check bill id
        if (reqBillID == null || reqBillID.length() < 1) {
            //if bill id is null, redirects to root
            response.sendRedirect("/");
            return;
        }
        else
        {
            try{
                Integer.parseInt(reqBillID);
                billID = reqBillID;
                BillModel billModel = new BillModel();
                Bill temp = billModel.getBill(Integer.parseInt(billID));
                if(temp==null){
                    response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
                    return;
                }
                else
                    bill = temp;
            }
            catch (Exception ex){
                //if bill id is not an integer, redirects to root
                response.sendRedirect("/");
                return;
            }
        }
        
        //Determine type of page 
        String type = request.getParameter("type");
        try {
            switch (type) {
                case "index":
                    //Show all bill
                    index(request, response);
                    break;
                case "delete":
                    delete(request, response);
                    break;
                case "new":
                    //Render new bill page
                    bdnew(request, response);
                    break;

                case "insert":
                    //Process insert new bill
                    insert(request, response);
                    break;
                case "edit":
                    //Process render edit page
                    edit(request, response);
                    break;
                case "update":
                    //Process update data
                    update(request, response);
                    break;


                }
            }catch (IOException | TemplateException exception) {
            }

    }
    
    private void index(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        
        //Load template file
        TemplateLoader templateLoader = TemplateResourceLoader.create("fresher/");
        Template template = templateLoader.getTemplate("/view/bill_detail.xtm");
        TemplateDataDictionary dictionary = TemplateDictionary.create();
        dictionary.setVariable("billID", billID);
        
        //Get Bill Info
        Date dt = new Date(bill.getDate()*1000);
        SimpleDateFormat ft = new SimpleDateFormat ("dd/MM/yyyy");
        dictionary.setVariable("billTable", String.valueOf(bill.getTableId()));
        dictionary.setVariable("billDate", ft.format(dt));
        dictionary.setVariable("billTotal", String.valueOf(bill.getTotal()));
        
        //Get All Details of Bill
        BillDetailModel billDetailModel = new BillDetailModel();
        ArrayList<BillDetail> details = billDetailModel.getDetailsOfBill(billID);

        
        for (int i = 0; i < details.size(); i++) {
            //create a section to store object
            TemplateDataDictionary bDetails = dictionary.addSection("details");

            //set variable to section
            BillDetail current = details.get(i);
            bDetails.setVariable("details.id", Integer.toString(current.getId()));
            bDetails.setVariable("details.billID", Integer.toString(current.getBillID()));
            bDetails.setVariable("details.food", current.getFood());
            bDetails.setVariable("details.price", Integer.toString(current.getPrice()));
        }
        
        //Render output and output
        String content = template.renderToString(dictionary);
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println(content);
    }
    
    private void bdnew(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        //Load template file
        TemplateLoader templateLoader = TemplateResourceLoader.create("fresher/");
        Template template = templateLoader.getTemplate("/view/bill_detail_insert.xtm");
        TemplateDataDictionary dictionary = TemplateDictionary.create();
        dictionary.setVariable("billID", billID);
        
        //Render output and output
        String content = template.renderToString(dictionary);
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println(content);
    }
    
    private void insert(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        //System.out.println("Doing Insert\n");
        
        //Get and check Params
        int price =0;
        String reqFood = request.getParameter("food");
        String reqPrice = request.getParameter("price");
        
        try{
            price = Integer.parseInt(reqPrice);
            if(price<0){
                response.sendRedirect("/bill-detail?bid="+billID+"&type=new");
                return;
            }
        }
        catch (Exception ex){
            //if bill id is not an integer, redirects to index
            response.sendRedirect("/bill-detail?bid="+billID+"&type=new");
            return;
        }
        
        //Process add detail
        BillDetailModel billDetailModel = new BillDetailModel();
        if(billDetailModel.addDetailsToBill(billID, reqFood, reqPrice)){
            int total = billDetailModel.getTotalOfBill(Integer.parseInt(billID));
            BillModel billModel = new BillModel();
            billModel.updateTotalOfBill(Integer.parseInt(billID), total);
        }
        
        //Redirect to index page
        response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
    }
    
    private void edit(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        //Get and check Bill Details ID
        String reqDetailID = request.getParameter("bdid");
        
        if (reqDetailID == null || reqDetailID.length() < 1) {
            //if bill id is null, redirects to index
            response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
            return;
        }
        else
        {
            try{
                Integer.parseInt(reqDetailID);
            }
            catch (Exception ex){
                //if bill id is not an integer, redirects to index
                response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
                return;
            }
        }
        
        //Load Detail Info
        BillDetailModel billDetailModel = new BillDetailModel();
        BillDetail detail = billDetailModel.getDetailByID(reqDetailID);
        
        if (detail == null){ //no detail found
            response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
            return;
        }
        else if (detail.getBillID() != Integer.parseInt(billID)){ //bill id is wrong
            response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
            return;
        }
        
        //Load template file
        TemplateLoader templateLoader = TemplateResourceLoader.create("fresher/");
        Template template = templateLoader.getTemplate("/view/bill_detail_edit.xtm");
        TemplateDataDictionary dictionary = TemplateDictionary.create();
        dictionary.setVariable("billID", billID);
        dictionary.setVariable("detailID", reqDetailID);
        dictionary.setVariable("food", detail.getFood());
        dictionary.setVariable("price", String.valueOf(detail.getPrice()));
        
        //Render output and output
        String content = template.renderToString(dictionary);
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println(content);
    }
    
    private void update(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        //Get and check Bill Details ID
        String reqDetailID = request.getParameter("bdid");
        
        if (reqDetailID == null || reqDetailID.length() < 1) {
            //if bill id is null, redirects to index
            response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
            return;
        }
        else
        {
            try{
                Integer.parseInt(reqDetailID);
            }
            catch (Exception ex){
                //if bill id is not an integer, redirects to index
                response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
                return;
            }
        }
        
        //Get and check Params
        int price =0;
        String reqFood = request.getParameter("food");
        String reqPrice = request.getParameter("price");
        
        try{
            price = Integer.parseInt(reqPrice);
            if(price<0){
                response.sendRedirect("/bill-detail?bid="+billID+"&bdid="+reqDetailID+"&type=edit");
                return;
            }
        }
        catch (Exception ex){
            //if bill id is not an integer, redirects to index
            response.sendRedirect("/bill-detail?bid="+billID+"&bdid="+reqDetailID+"&type=edit");
            return;
        }
        
        //Process Update
        BillDetailModel billDetailModel = new BillDetailModel();
        if (billDetailModel.updateBillDetail(reqDetailID,reqFood,reqPrice)){
            int total = billDetailModel.getTotalOfBill(Integer.parseInt(billID));
            BillModel billModel = new BillModel();
            billModel.updateTotalOfBill(Integer.parseInt(billID), total);
        }
       
        //Redirects to index
        response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
        
    }
    
    private void delete(HttpServletRequest request,
            HttpServletResponse response) throws IOException, TemplateException {
        
        //Get and check Bill Details ID
        String reqDetailID = request.getParameter("bdid");
        
        if (reqDetailID == null || reqDetailID.length() < 1) {
            //if bill id is null, redirects to index
            response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
            return;
        }
        else
        {
            try{
                Integer.parseInt(reqDetailID);
            }
            catch (Exception ex){
                //if bill id is not an integer, redirects to index
                response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
                return;
            }
        }
        
        //Process Delete
        BillDetailModel billDetailModel = new BillDetailModel();
        if(billDetailModel.deleteBillDetail(reqDetailID)){
            int total = billDetailModel.getTotalOfBill(Integer.parseInt(billID));
            BillModel billModel = new BillModel();
            billModel.updateTotalOfBill(Integer.parseInt(billID), total);
        }
       
        //Redirects to index
        response.sendRedirect("/bill-detail?bid="+billID+"&type=index");
    }
}
